import { VuexModule, Module, Action, Mutation, getModule } from 'vuex-module-decorators'
import { login } from '@/api/login'
import { getToken, removeToken, setToken } from '@/utils/auth'
import store from '@/store'
export interface IUserState {
    token: string
    name: string
    roles: string[],
    permissions: string[]
}

@Module({ dynamic: true, store, name: 'user' })
class User extends VuexModule implements IUserState {
  public token = getToken() || ''
  public name = ''
  public introduction = ''
  public roles: string[] = []
  public permissions: string[] = []

  @Mutation
  private SET_TOKEN (token: string) {
    this.token = token
  }

  @Mutation
  private SET_NAME (name: string) {
    this.name = name
  }

  @Mutation
  private SET_ROLES (roles: string[]) {
    this.roles = roles
  }

  @Mutation
  private SET_PERMISSIONS (permissions: string[]) {
    this.permissions = permissions
  }

  @Action
  public async Login (userInfo: { loginName: string|undefined|null, password: string|undefined|null }) {
    const data: any = await login(userInfo)
    if (data.token) {
      localStorage.setItem('adminId', data.adminId)
      setToken(data.token)
      this.SET_TOKEN(data.token)
      return { success: true }
    } else {
      return { success: false }
    }
  }

  @Action
  public async LogOut () {
    if (this.token === '') {
      throw Error('LogOut: token is undefined!')
    }
    // await logout()
    removeToken()
    this.SET_TOKEN('')
    this.SET_ROLES([])
  }
}
export const UserModule = getModule(User)
